package com.hqyj.mana.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hqyj.mana.enums.ResultEnum;
import com.hqyj.mana.pojo.HrManagement;
import com.hqyj.mana.pojo.User;
import com.hqyj.mana.pojo.vo.ResultVO;
import com.hqyj.mana.service.SecurityService;

@RestController
@RequestMapping("security")
public class SecurityController {
	@Autowired
	private SecurityService securityService;
	@RequestMapping("login.do")
	public ResultVO login(HttpServletRequest request, User user){
		ResultVO resultVO = new ResultVO();
		HttpSession session = request.getSession();
		System.out.println(user.getPassword());
		User result = null;
		try{
			result = securityService.login(user);
		}catch(Exception e){
			resultVO.setCode(ResultEnum.USER_NOT_FOUND.getCode());
			resultVO.setMsg(ResultEnum.USER_NOT_FOUND.getMessage());
			return resultVO;
		}
		resultVO.setData(result);
		if(result != null){
			session.setAttribute("CURRENT_USER",result.getRoleId());
			resultVO.setCode(ResultEnum.SUCCESS.getCode());
			resultVO.setMsg(ResultEnum.SUCCESS.getMessage());
			return resultVO;
		}
		resultVO.setCode(ResultEnum.PARAM_ERROR.getCode());
		resultVO.setMsg(ResultEnum.PARAM_ERROR.getMessage());
		return resultVO;
	}
	@RequestMapping("register.do")
	public ResultVO register(User user){
		ResultVO resultVO = new ResultVO();
		int result = securityService.register(user);
		resultVO.setData(result);
		if(result==0){
			resultVO.setCode(ResultEnum.PARAM_ERROR.getCode());
			resultVO.setMsg(ResultEnum.PARAM_ERROR.getMessage());
			return resultVO;
		}
		resultVO.setCode(ResultEnum.SUCCESS.getCode());
		resultVO.setMsg(ResultEnum.SUCCESS.getMessage());
		return resultVO;
	}
	
	@RequestMapping("updatepwd.do")
	public ResultVO updatepwd(User user){
		ResultVO resultVO = new ResultVO();
		int result = securityService.updatepwd(user);
		resultVO.setData(result);
		if(result==0){
			resultVO.setCode(ResultEnum.PARAM_ERROR.getCode());
			resultVO.setMsg(ResultEnum.PARAM_ERROR.getMessage());
			return resultVO;
		}
		resultVO.setCode(ResultEnum.SUCCESS.getCode());
		resultVO.setMsg(ResultEnum.SUCCESS.getMessage());
		return resultVO;
	}
	
	@RequestMapping("logout.do")
	public ResultVO logout(HttpServletRequest request){
		HttpSession session = request.getSession();
        session.removeAttribute("CURRENT_USER");
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(ResultEnum.SUCCESS.getCode());
		resultVO.setMsg(ResultEnum.SUCCESS.getMessage());
		return resultVO;
	}
}
